package com.hunit.mqtt_dome.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hunit.mqtt_dome.emqx.MqttSendClient;
import com.hunit.mqtt_dome.service.MqttMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description : MQTT消息服务接口实现
 * @Author : Sherlock
 * @Date : 2023/8/1 17:30
 */
@Service
public class MqttMessageServiceImpl implements MqttMessageService {

    private static final Logger logger = LoggerFactory.getLogger(MqttMessageServiceImpl.class);

    @Autowired
    private MqttSendClient mqttSendClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean sendMessage(String topic, String message) {
        return sendMessage(topic, message, false);
    }

    @Override
    public boolean sendMessage(String topic, String message, boolean retained) {
        try {
            logger.info("发送MQTT消息，主题: {}, 消息内容: {}, 是否保留: {}", topic, message, retained);
            boolean result = mqttSendClient.publish(retained, topic, message);
            if (result) {
                logger.info("MQTT消息发送成功");
            } else {
                logger.error("MQTT消息发送失败");
            }
            return result;
        } catch (Exception e) {
            logger.error("MQTT消息发送异常: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean sendJsonMessage(String topic, Object jsonObject) {
        return sendJsonMessage(topic, jsonObject, false);
    }

    @Override
    public boolean sendJsonMessage(String topic, Object jsonObject, boolean retained) {
        try {
            String jsonMessage = objectMapper.writeValueAsString(jsonObject);
            logger.info("发送JSON格式MQTT消息，主题: {}, 消息内容: {}, 是否保留: {}", topic, jsonMessage, retained);
            return sendMessage(topic, jsonMessage, retained);
        } catch (JsonProcessingException e) {
            logger.error("JSON序列化异常: {}", e.getMessage(), e);
            return false;
        }
    }
} 